package com.baidu.ai.aip.service.impl;

import com.baidu.ai.aip.domain.AiToken;
import com.baidu.ai.aip.mapper.BaiduMapper;
import com.baidu.ai.aip.service.BaiduService;
import com.baidu.ai.aip.utils.GsonUtils;
import com.ruoyi.common.utils.DateUtils;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class BaiduServiceImpl implements BaiduService {
   private final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();
   private final String tokenUrl = "https://aip.baidubce.com/oauth/2.0/token";
   private final String grantType = "client_credentials";
   private final String clientId = "OX3aXqXxP7q3r75AHf7qpy8s";
   private final String clientSecret = "QmZoi3guCS9BvLVGphYVlmZIPEI59q6A";

    @Autowired
    private BaiduMapper baiduMapper;

    @Override
    public String getToken() {
        final List<AiToken> tokens = baiduMapper.getToken();
        Date dateNow = DateUtils.getNowDate();
        if(tokens != null && tokens.size()  >0){
            /**
             * 获取当生成时间
             * 获取有效天数
             * 获取当前时间
             * 生成时间+有效时间< 当前时间有效，否则重新获取
             */
            AiToken token = tokens.get(0);

            final Date applyDate = token.getApplyDate();
            final int daysDiff = DateUtils.differentDaysByMillisecond(dateNow, applyDate);
            if(daysDiff <token.getDays()){
                return token.getToken();
            }else{
                final Map tokenFromBaidu = getTokenFromBaidu();
                final int id = token.getId();
                final long expiresIn = (long)Double.parseDouble(tokenFromBaidu.get("expires_in").toString());
                final int expiresInDays = DateUtils.convertsecondsToDays(expiresIn);
                final String accessToken = tokenFromBaidu.get("access_token").toString();
                AiToken tokenObj = new AiToken();
                tokenObj.setApplyDate(dateNow);
                tokenObj.setToken(accessToken);
                tokenObj.setDays(expiresInDays);
                tokenObj.setId(id);
                int i = baiduMapper.updateToken(tokenObj);
                return accessToken;
            }
        }else {
            final Map tokenFromBaidu = getTokenFromBaidu();
            final long expiresIn = (long)Double.parseDouble(tokenFromBaidu.get("expires_in").toString());
            final int expiresInDays = DateUtils.convertsecondsToDays(expiresIn);
            final String accessToken = tokenFromBaidu.get("access_token").toString();
            AiToken tokenObj = new AiToken();
            tokenObj.setApplyDate(dateNow);
            tokenObj.setToken(accessToken);
            tokenObj.setDays(expiresInDays);
            int i = baiduMapper.insertToken(tokenObj);
            return accessToken;
        }

    }

    @Override
    public int updateToken(AiToken tokenObj) {
        return baiduMapper.updateToken(tokenObj);
    }

    @Override
    public int insertToken(AiToken tokenObj) {
        return baiduMapper.insertToken(tokenObj);
    }

    /**
     * 从百度获取新token
     * @return
     */
    private Map getTokenFromBaidu()  {

        StringBuffer sb = new StringBuffer();
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, "");
        Request request = new Request.Builder()
                .url(sb.append(tokenUrl)
                        .append("?client_id=")
                        .append(clientId)
                        .append("&client_secret=")
                        .append(clientSecret)
                        .append( "&grant_type=client_credentials").toString())
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .addHeader("Accept", "application/json")
                .build();
        Response response = null;
        try {
            response = HTTP_CLIENT.newCall(request).execute();
        } catch (IOException e) {
            System.out.println("###########从百度获取token失败！");
            e.printStackTrace();
        }
        /**
         * 对返回的json解析
         */
        try{
            final String resp = response.body().string();
//            final String s = GsonUtils.toJson(resp);
            final Map map = GsonUtils.fromJson(resp, Map.class);
            return map;
        }catch (IOException ex){
            System.out.println("com.baidu.ai.aip.service.impl.BaiduServiceImpl:response.body().string()");
            ex.printStackTrace();
            return null;
        }

//        return map;
    }
}
